package com.itheima.controller;


import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Sports;
import com.itheima.service.SportsService;
import com.itheima.utils.POIUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/sports")
public class SportsController {
    @Reference
    private SportsService sportsService;

    @PreAuthorize("hasAuthority('SPORT_ADD')")
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            if(list!=null&&list.size()>0){
                for (String[] strings : list) {
                    Sports sports = new Sports(strings[0], strings[1], strings[2], strings[3]);
                    sportsService.add(sports);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_SPORTS_FAIL);
        }
        return new Result(true,MessageConstant.IMPORT_SPORTS_SUCCESS);
    }

    @PreAuthorize("hasAuthority('SPORT_QUERY')")
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return sportsService.queryPage(queryPageBean);
    }

    @PreAuthorize("hasAuthority('SPORT_ADD')")
    @RequestMapping("/add")
    public Result add(@RequestBody Sports sports) {
        try {
            sportsService.add(sports);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SPORTS_FALL);
        }
        return new Result(true, MessageConstant.ADD_SPORTS_SUCCESS);
    }
}
